package com.weixin.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.google.common.collect.Maps;
import com.weixin.util.GsonUtil;

public class ParamsFilter implements Filter {
	private static Logger logger = Logger.getLogger(ParamsFilter.class);

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		try {
			HttpServletRequest httprequest = (HttpServletRequest) request;
			Map<String, String> headerMap = Maps.newHashMap();
			Map<String, String> paramsMap = Maps.newHashMap();

			Enumeration<String> headers = httprequest.getHeaderNames();
			while (headers.hasMoreElements()) {
				try {
					String headerName = headers.nextElement();
					String headerValue = URLDecoder.decode(
							httprequest.getHeader(headerName), "UTF-8");
					headerMap.put(headerName, headerValue);

				} catch (UnsupportedEncodingException e) {
					logger.error(e, e);
				}
			}

			Enumeration<String> paramterNames = request.getParameterNames();
			while (paramterNames.hasMoreElements()) {
				try {
					String paramterName = paramterNames.nextElement();
					String paramterValue = URLDecoder.decode(
							request.getParameter(paramterName), "UTF-8");
					paramsMap.put(paramterName, paramterValue);
				} catch (UnsupportedEncodingException e) {
					logger.error(e, e);
				}
			}
			logger.debug("headerMap:" + GsonUtil.toJson(headerMap));
			logger.debug("paramsMap:" + GsonUtil.toJson(paramsMap));
			chain.doFilter(request, response);
		} catch (Exception e) {

		} finally {

		}
	}

	public void destroy() {

	}

	public void init(FilterConfig arg0) throws ServletException {
		/*
		 * String filePath = this.getClass().getResource("/").getPath(); //
		 * 找到log4j.properties配置文件所在的目录(已经创建好) filePath =
		 * filePath.substring(1).replace("bin", "src");
		 * PropertyConfigurator.configure(filePath+"log4j.properties");
		 */
	}
}